﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GtsServer.Common;
using GtsServer.DAL;
using System.Data;
using System.Timers;

namespace GtsServer.Service.TaskStartEndService
{
    public class LotteryPoolController
    {
        private static LotteryPoolController lotteryController = null;
        static object objLock = new object();

        int editTime = 0;//更新时间（单位秒）
        int editNum = 0;//更新数量

        LotteryPoolDAL dal = new LotteryPoolDAL();
        Timer startTimer = null;

        public static LotteryPoolController GetInstance()
        {
            if (lotteryController == null)
            {
                lock (objLock)
                {
                    if (lotteryController == null)
                        lotteryController = new LotteryPoolController();
                }
            }
            return lotteryController;
        }

        public LotteryPoolController()
        {
            LogHelper.WriteLog("彩池任务定时加彩蛋服务正在启动...");
            Load();
            LogHelper.WriteLog("彩池任务定时加彩蛋服务已开启！每隔" + editTime + "秒，更新彩蛋：" + editNum);
        }

        /// <summary>
        /// 更改更新时间及更新数量
        /// </summary>
        /// <param name="time">时间间隔（秒）</param>
        /// <param name="num">更新数量</param>
        public void Edit(int time, int num)
        {

            editNum = editNum != num ? num : editNum;
            if (editTime != time)
            {
                if (time == 0)
                    startTimer.Stop();
                else if (editTime == 0)
                {
                    startTimer.Interval = time * 1000;
                    startTimer.Start();
                }
                else
                    startTimer.Interval = time * 1000;

                editTime = time;
            }
        }

        public void Load()
        {
            DataSet ds = new DataSet();
            ds = dal.GetList(string.Empty);
            editTime = Convert.ToInt32(ds.Tables[0].Rows[0]["EditTime"].ToString());
            editNum = Convert.ToInt32(ds.Tables[0].Rows[0]["EditNum"].ToString());

            if (editTime != 0)
            {
                startTimer = new Timer(editTime * 1000);
                startTimer.Elapsed += new ElapsedEventHandler(StartTimer_Elapsed);
                startTimer.Start();
            }
        }

        void StartTimer_Elapsed(object sender, ElapsedEventArgs e)
        {

            dal.UpdatePoolNum(editNum);
        }
    }
}
